package com.lxm.framework.web.jsonresult.handler;

import com.lxm.framework.common.AppException;
import com.lxm.framework.common.auth.errs.AbstractAuthException;
import com.lxm.framework.web.jsonresult.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Lys
 * @Date 2022/3/7
 * @Describe
 **/
@Slf4j
@RestControllerAdvice(basePackages = "com.lxm")
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JsonResult<?> allExceptions(HttpServletRequest req, HttpServletResponse res, Exception e) {
        log.error("global exception handler ,uri : {}, exception : {}", req.getRequestURI(), e.getMessage());
        res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return JsonResult.json(-1, e.getMessage());
    }

    @ExceptionHandler(AppException.class)
    public JsonResult<?> handleAppException(HttpServletRequest req, HttpServletResponse res, AppException e) {
        log.debug("global exception handler ,uri :{} , app-exception : {}", req.getRequestURI(), e);
        res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return JsonResult.json(500, e.getMessage());
    }

    @ExceptionHandler(AbstractAuthException.class)
    public JsonResult<?> handleAuthException(HttpServletRequest req, HttpServletResponse res, AbstractAuthException e) {
        log.debug("global exception handler ,uri :{} , app-exception : {}", req.getRequestURI(), e.getMessage());
        if (1001 == e.getCode()) {
            res.setStatus(HttpStatus.UNAUTHORIZED.value());
        } else if (1002 == e.getCode()) {
            res.setStatus(HttpStatus.FORBIDDEN.value());
        } else {
            res.setStatus(HttpStatus.OK.value());
        }
        return JsonResult.json(e.getCode(), e.getMessage());
    }


}
